<!DOCTYPE HTML>
<html lang="zh-Hans" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>一步步实现 Rust Bevy ECS 的 System 简化版本 - Rust 优秀博文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">
        <link rel="stylesheet" href="../../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">1.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow.html"><strong aria-hidden="true">1.1.</strong> Rust Concept Clarification Deref vs AsRef vs Borrow vs Cow</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Deref_AsRef_Borrow_Cow释义.html"><strong aria-hidden="true">1.2.</strong> Deref AsRef Borrow Cow 释义</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然.html"><strong aria-hidden="true">1.3.</strong> Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Cow类型有什么用？详解Cow及其用途/Rust的Cow类型有什么用？详解Cow及其用途.html"><strong aria-hidden="true">1.4.</strong> Rust的Cow类型有什么用？详解Cow及其用途</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/判别Fn、FnMut、FnOnce的标准/判别Fn、FnMut、FnOnce的标准.html"><strong aria-hidden="true">1.5.</strong> 判别Fn、FnMut、FnOnce的标准</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/一行代码告诉你内部可变性的真相(UnsafeCell)/一行代码告诉你内部可变性的真相(UnsafeCell).html"><strong aria-hidden="true">1.6.</strong> 一行代码告诉你内部可变性的真相(UnsafeCell)</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Tour_of_Rust's_Standard_Library_Traits/Tour_of_Rust's_Standard_Library_Traits.html"><strong aria-hidden="true">1.7.</strong> Tour of Rust's Standard Library Traits</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/逆变、协变与子类型，以及Rust/逆变、协变与子类型，以及Rust.html"><strong aria-hidden="true">1.8.</strong> 逆变、协变与子类型，以及Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust自引用结构、Pin与Unpin/Rust自引用结构、Pin与Unpin.html"><strong aria-hidden="true">1.9.</strong> Rust自引用结构、Pin与Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/为什么Rust需要Pin,Unpin/为什么Rust需要Pin,Unpin.html"><strong aria-hidden="true">1.10.</strong> 译：为什么 Rust 需要 Pin, Unpin ？</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/定海神针Pin和Unpin/定海神针Pin和Unpin.html"><strong aria-hidden="true">1.11.</strong> 译：定海神针 Pin 和 Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/sizedness-in-rust/sizedness-in-rust.html"><strong aria-hidden="true">1.12.</strong> Sizedness in Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust生命周期集大成者PhantomData〈T〉/Rust生命周期集大成者PhantomData〈T〉.html"><strong aria-hidden="true">1.13.</strong> Rust生命周期集大成者 PhantomData&lt;T&gt;</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操_Part_0.html"><strong aria-hidden="true">1.14.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操 Part 0</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：GAT实现引用类型关联_Part_1.html"><strong aria-hidden="true">1.15.</strong> 数据库表达式执行的黑魔法：GAT实现引用类型关联 Part 1</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用HRTB写bound_Part_2.html"><strong aria-hidden="true">1.16.</strong> 数据库表达式执行的黑魔法：用HRTB写bound Part 2</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&_4.html"><strong aria-hidden="true">1.17.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码 Part 3 & 4</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化_Part_5_&_6.html"><strong aria-hidden="true">1.18.</strong> 数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 & 6</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html"><strong aria-hidden="true">1.19.</strong> 数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型 Part 7</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">2.</strong> 生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../02_生命周期/Rust中的生命周期——从StrSplit实例说开去/Rust中的生命周期——从StrSplit实例说开去.html"><strong aria-hidden="true">2.1.</strong> Rust中的生命周期——从StrSplit实例说开去</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/与ChatGPT深度对话来学Rust生命周期/与ChatGPT深度对话来学Rust生命周期.html"><strong aria-hidden="true">2.2.</strong> 与ChatGPT深度对话来学Rust生命周期</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（1）/进击的Rust生命周期——early_bound与late_bound（1）.html"><strong aria-hidden="true">2.3.</strong> 进击的Rust生命周期——early_bound与late_bound（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（2）/进击的Rust生命周期——early_bound与late_bound（2）.html"><strong aria-hidden="true">2.4.</strong> 进击的Rust生命周期——early_bound与late_bound（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（1）/进击的Rust生命周期——一力降十会的MIR（1）.html"><strong aria-hidden="true">2.5.</strong> 进击的Rust生命周期——一力降十会的MIR（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（2）/进击的Rust生命周期——一力降十会的MIR（2）.html"><strong aria-hidden="true">2.6.</strong> 进击的Rust生命周期——一力降十会的MIR（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Common_Rust_Lifetime_Misconceptions/Common_Rust_Lifetime_Misconceptions.html"><strong aria-hidden="true">2.7.</strong> Common Rust Lifetime Misconceptions</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Rust生命周期常见误区/Rust生命周期常见误区.html"><strong aria-hidden="true">2.8.</strong> 译：Rust生命周期常见误区</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">3.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html"><strong aria-hidden="true">3.1.</strong> 简单写个Rust无锁队列</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——混合自旋锁/进击的Rust多线程——混合自旋锁.html"><strong aria-hidden="true">3.2.</strong> 进击的Rust多线程——混合自旋锁</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/An_unsafe_tour_of_Rust's_Send_and_Sync/An_unsafe_tour_of_Rust's_Send_and_Sync.html"><strong aria-hidden="true">3.3.</strong> An unsafe tour of Rust's Send and Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——Send与Sync/进击的Rust多线程——Send与Sync.html"><strong aria-hidden="true">3.4.</strong> 进击的Rust多线程——Send与Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——离经叛道的PhantomData/进击的Rust多线程——离经叛道的PhantomData.html"><strong aria-hidden="true">3.5.</strong> 进击的Rust多线程——离经叛道的PhantomData</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust_Async_Pin概念解析/Rust_Async_Pin概念解析.html"><strong aria-hidden="true">3.6.</strong> Rust Async: Pin概念解析</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust和C++的并发库对比/Rust和C++的并发库对比.html"><strong aria-hidden="true">3.7.</strong> 译：Rust 和 C++ 的并发库对比</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust原子类型和内存排序/Rust原子类型和内存排序.html"><strong aria-hidden="true">3.8.</strong> Rust原子类型和内存排序</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">4.</strong> 网络编程</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../06_网络编程/从编解码层面理解WebSocket_手写一个WebSocket/从编解码层面理解WebSocket_手写一个WebSocket.html"><strong aria-hidden="true">4.1.</strong> 从编解码层面理解WebSocket 手写一 个WebSocket</a></li><li class="chapter-item expanded "><a href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html"><strong aria-hidden="true">4.2.</strong> 透过Rust探索系统的本原：网络篇</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">5.</strong> 轮子系列</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html"><strong aria-hidden="true">5.1.</strong> 700行Rust写一个内存分配器</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust：网络库的实现思路/Rust：网络库的实现思路.html"><strong aria-hidden="true">5.2.</strong> Rust：网络库的实现思路</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html"><strong aria-hidden="true">5.3.</strong> Rust异步运行时基础部件</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（1）.html"><strong aria-hidden="true">5.4.</strong> 使用Rust+epoll编写异步IO框架（1）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（2）.html"><strong aria-hidden="true">5.5.</strong> 使用Rust+epoll编写异步IO框架（2）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（3）.html"><strong aria-hidden="true">5.6.</strong> 使用Rust+epoll编写异步IO框架（3）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day1.html"><strong aria-hidden="true">5.7.</strong> 用rust从零开发一套web框架：day1</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html"><strong aria-hidden="true">5.8.</strong> 用rust从零开发一套web框架：day2</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day3.html"><strong aria-hidden="true">5.9.</strong> 用rust从零开发一套web框架：day3</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html"><strong aria-hidden="true">5.10.</strong> 用rust从零开发一套web框架：day4</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day5.html"><strong aria-hidden="true">5.11.</strong> 用rust从零开发一套web框架：day5</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">6.</strong> 奇技淫巧</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Copy-On-Write是不是优化？/Copy-On-Write是不是优化？.html"><strong aria-hidden="true">6.1.</strong> 译：Copy-On-Write是不是优化？</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/揭秘神奇的Rust_Axum风格的函数实现/揭秘神奇的Rust_Axum风格的函数实现.html"><strong aria-hidden="true">6.2.</strong> 译：揭秘神奇的 Rust Axum 风格的函数实现</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/“变长参数”函数与回调/“变长参数”函数与回调.html"><strong aria-hidden="true">6.3.</strong> “变长参数”函数与回调</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Rust字符串格式化的幕后：format_args!()/Rust字符串格式化的幕后：format_args!().html"><strong aria-hidden="true">6.4.</strong> 译：Rust字符串格式化的幕后：format_args!()</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html"><strong aria-hidden="true">6.5.</strong> 给Rust带来一点C++特产</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html" class="active"><strong aria-hidden="true">6.6.</strong> 一步步实现 Rust Bevy ECS 的 System 简化版本</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html"><strong aria-hidden="true">6.7.</strong> Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">7.</strong> 源码分析</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：bytes源码分析/Rust并发：bytes源码分析.html"><strong aria-hidden="true">7.1.</strong> Rust并发：bytes源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库Arc源码分析/Rust并发：标准库Arc源码分析.html"><strong aria-hidden="true">7.2.</strong> Rust并发：标准库Arc源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库sync_Once源码分析/Rust并发：标准库sync_Once源码分析.html"><strong aria-hidden="true">7.3.</strong> Rust并发：标准库sync::Once源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：引用计数Rc/Rust源码阅读：引用计数Rc.html"><strong aria-hidden="true">7.4.</strong> Rust源码阅读：引用计数Rc</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html"><strong aria-hidden="true">7.5.</strong> Rust源码阅读： Cell、RefCell与内部可变性</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/关于_Rust_的_UnsafeCell、Cell_与_RefCell/关于_Rust_的_UnsafeCell、Cell_与_RefCell.html"><strong aria-hidden="true">7.6.</strong> 关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html"><strong aria-hidden="true">7.7.</strong> Rust Async: async-stream源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/走进Tokio的异步世界/走进Tokio的异步世界.html"><strong aria-hidden="true">7.8.</strong> 走进 Tokio 的异步世界</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/tokio.rs_runtime的实现/tokio.rs_runtime的实现.html"><strong aria-hidden="true">7.9.</strong> tokio.rs runtime 的实现</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/Tokio_internals.html"><strong aria-hidden="true">7.10.</strong> Tokio internals</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/译文：Tokio內部机制.html"><strong aria-hidden="true">7.11.</strong> 译：Tokio 内部机制</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Axum_HTTP_框架的架构分析/Rust_Axum_HTTP_框架的架构分析.html"><strong aria-hidden="true">7.12.</strong> Rust Axum HTTP 框架的架构分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/安利一个Rust_Game_Engine：Bevy--ECS部分/安利一个Rust_Game_Engine：Bevy--ECS部分.html"><strong aria-hidden="true">7.13.</strong> 安利一个Rust Game Engine：Bevy--ECS部分</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_解析之任务调度/Tokio_解析之任务调度.html"><strong aria-hidden="true">7.14.</strong> Tokio 解析之任务调度</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">8.</strong> 生态观察</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../11_生态观察/Rust_web_frameworks_have_subpar_error_reporting/Rust_web_frameworks_have_subpar_error_reporting.html"><strong aria-hidden="true">8.1.</strong> Rust web frameworks have subpar error reporting</a></li><li class="chapter-item expanded "><a href="../../11_生态观察/SeaORM：要做Rust版本的ActiveRecord/SeaORM：要做Rust版本的ActiveRecord.html"><strong aria-hidden="true">8.2.</strong> SeaORM：要做Rust版本的ActiveRecord</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">9.</strong> 死灵终极</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_总述.html"><strong aria-hidden="true">9.1.</strong> 译：Learn Rust the Dangerous Way 总述</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_0.html"><strong aria-hidden="true">9.2.</strong> 译：Learn Rust the Dangerous Way 0</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_1.html"><strong aria-hidden="true">9.3.</strong> 译：Learn Rust the Dangerous Way 1</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_2.html"><strong aria-hidden="true">9.4.</strong> 译：Learn Rust the Dangerous Way 2</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_3.html"><strong aria-hidden="true">9.5.</strong> 译：Learn Rust the Dangerous Way 3</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_4.html"><strong aria-hidden="true">9.6.</strong> 译：Learn Rust the Dangerous Way 4</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_5.html"><strong aria-hidden="true">9.7.</strong> 译：Learn Rust the Dangerous Way 5</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（一）.html"><strong aria-hidden="true">9.8.</strong> Unsafe Rust 随堂小测（一）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（二）.html"><strong aria-hidden="true">9.9.</strong> Unsafe Rust 随堂小测（二）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（三）.html"><strong aria-hidden="true">9.10.</strong> Unsafe Rust 随堂小测（三）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测参考答案.html"><strong aria-hidden="true">9.11.</strong> Unsafe Rust 随堂小测参考答案</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Rust 优秀博文</h1>

                    <div class="right-buttons">
                        <a href="../../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="一步步实现-rust-bevy-ecs-的-system-简化版本"><a class="header" href="#一步步实现-rust-bevy-ecs-的-system-简化版本">一步步实现 Rust Bevy ECS 的 System 简化版本</a></h1>
<p>原载：<a href="https://zhuanlan.zhihu.com/p/595218713">https://zhuanlan.zhihu.com/p/595218713</a></p>
<p>作者：<a href="https://www.zhihu.com/people/yi-ci-yuan-33-29">异次元</a></p>
<p>在阅读 Rust Bevy 代码时，我学到了很多</p>
<p>当我接触到Rust Bevy 中的System时，就感觉它十分强大，就很好奇它是如何实现的</p>
<p>下面，我们将一步步实现一个简化版本，命名与<code>Bevy ECS</code>相同，所以读完此篇文章之后对<code>Bevy</code>相关代码的阅读也就没有什么障碍了</p>
<blockquote>
<p>文章参考的 bevy 版本：0.9 bevy: <a href="https://link.zhihu.com/?target=https%3A//github.com/bevyengine/bevy">https://github.com/bevyengine/bevy</a></p>
</blockquote>
<h3 id="bevy-ecs-简单用例"><a class="header" href="#bevy-ecs-简单用例">Bevy ECS 简单用例</a></h3>
<p>Bevy ECS 简单用例：</p>
<pre><pre class="playground"><code class="language-rust">use bevy::prelude::*;

fn main() {
    App::new()
      .add_system(hello_world_system)
      .add_system(test)
      .run();
}

fn hello_world_system() {
    println!(&quot;hello world&quot;);
}
fn test(mut commands: Commands, input: Res&lt;Input&lt;KeyCode&gt;&gt;, entites: Query&lt;Entity&gt;) {}
</code></pre></pre>
<p>如上面代码所示，<code>Bevy</code>实现了可以将不定参数数量的函数作为<code>System</code>添加到<code>App</code>中，而函数的参数则表明了此<code>System</code>需要获取的对象，十分灵活，一些 Rust Web框架也有类似的机制</p>
<h3 id="尝试实现它"><a class="header" href="#尝试实现它">尝试实现它</a></h3>
<p>通过上面的用例，能写出如下代码：</p>
<pre><pre class="playground"><code class="language-rust">pub trait System {
    fn run(&amp;mut self);
}

pub struct App {
    systems: Vec&lt;Box&lt;dyn System&gt;&gt;,
}

impl App {
    pub fn new() -&gt; Self {
        Self { systems: vec![] }
    }

    pub fn add_system&lt;T: System + 'static&gt;(&amp;mut self, system: T) -&gt; &amp;mut Self {
        self.systems.push(Box::new(system));
        self
    }

    pub fn run(&amp;mut self) {
        for item in self.systems.iter_mut() {
            item.run();
        }
    }
}

impl&lt;T: FnMut()&gt; System for T {
    fn run(&amp;mut self) {
        self();
    }
}

fn main() {
    App::new()
        .add_system(test_system)
        .add_system(test_system2)
        .run();
}

fn test_system() {
    println!(&quot;test_system&quot;);
}

fn test_system2() {
    println!(&quot;test_system2&quot;);
}
</code></pre></pre>
<p>代码能够成功运行<code>System</code>函数，但是<code>System</code>函数还不支持参数</p>
<h3 id="为不同参数的fnmut实现system"><a class="header" href="#为不同参数的fnmut实现system">为不同参数的<code>FnMut</code>实现<code>System</code></a></h3>
<p>暂时不考虑参数具体如何获取问题，先确保多参数能够编译成功</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;T: FnMut()&gt; System for T {
    fn run(&amp;mut self) {
        self();
    }
}

impl&lt;T: FnMut(u32)&gt; System for T { // 编译失败: conflicting implementations of trait `System`
    fn run(&amp;mut self) {
        self(2112);
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>上述代码添加了<code>u32</code>参数的支持，但是编译失败，<code>FuMut</code>不同参数属于同一trait，不能重复实现，即使能这样，也不现实，参数组合有很多种，不可能一一为它实现</p>
<p>于是想到为<code>System</code>参数做抽象，定义一个新的<code>trait</code>，<code>SystemParam</code>，有了如下代码：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait SystemParam {}

impl SystemParam for u32 {}
impl SystemParam for String {}
impl SystemParam for bool {}
<span class="boring">}
</span></code></pre></pre>
<p>之后，如果想要某种类型作为<code>System</code>的参数，为它实现<code>SystemParam</code>即可</p>
<p>用元组表示多个参数，<code>()</code>空元组表示无参数，多个参数: <code>(SystemParam,SystemParam,SystemParam)</code>，</p>
<pre><code>FnMut`无法满足我们的要求，为实现此效果，可以对`FnMut`进行包裹，定义一个新的`SystemParamFunction`，并为`FnMut`实现`SystemParamFunction
</code></pre>
<h3 id="systemparamfunction"><a class="header" href="#systemparamfunction">SystemParamFunction</a></h3>
<p>为<code>FnMut</code>实现<code>SystemParamFunction</code></p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait SystemParamFunction&lt;Param&gt;: 'static {
    fn run(&amp;mut self, params: Param);
}

impl&lt;F&gt; SystemParamFunction&lt;()&gt; for F
    where
        F: FnMut() + 'static,
{
    fn run(&amp;mut self, (): ()) {
        (self)();
    }
}

impl&lt;F, P0&gt; SystemParamFunction&lt;(P0,)&gt; for F
    where
        F: FnMut(P0) + 'static,
{
    fn run(&amp;mut self, (P0,): (P0,)) {
        (self)(P0);
    }
}
impl&lt;F, P0, P1&gt; SystemParamFunction&lt;(P0, P1)&gt; for F
    where
        F: FnMut(P0, P1) + 'static,
{
    fn run(&amp;mut self, (P0, P1): (P0, P1)) {
        (self)(P0, P1);
    }
}
impl&lt;F, P0, P1, P2&gt; SystemParamFunction&lt;(P0, P1, P2)&gt; for F
    where
        F: FnMut(P0, P1, P2) + 'static,
{
    fn run(&amp;mut self, (P0, P1, P2): (P0, P1, P2)) {
        (self)(P0, P1, P2);
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>有重复代码，此时使用宏去生成代码</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>macro_rules! impl_system_param_functions {
    ($($param: ident),*) =&gt; {
        impl&lt;F,$($param),*&gt; SystemParamFunction&lt;($($param,)*)&gt; for F
        where
            F: FnMut($($param),*) + 'static,
        {
            fn run(&amp;mut self, ($($param,)*): ($($param,)*)) {
                (self)($($param),*);
            }
        }
    };
}
impl_system_param_functions!();
impl_system_param_functions!(P0);
impl_system_param_functions!(P0,P1);
impl_system_param_functions!(P0,P1,P2);
<span class="boring">}
</span></code></pre></pre>
<p>现在好多了，但还是有重复，虽然并无大碍</p>
<p>但是这里还是去写一个通用的过程宏去生成它，之后还会用到，过程宏代码如下：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// 描述宏需要解析到的数据
struct AllTuples {
    macro_ident: Ident,
    start: usize,
    end: usize,
    ident: Ident,
}

impl Parse for AllTuples {
    fn parse(input: ParseStream) -&gt; Result&lt;Self&gt; {
        let macro_ident = input.parse::&lt;Ident&gt;()?; // 解析使用哪个宏定义
        input.parse::&lt;Comma&gt;()?;// 解析逗号
        let start = input.parse::&lt;LitInt&gt;()?.base10_parse()?; // 解析开始数字
        input.parse::&lt;Comma&gt;()?;// 解析逗号
        let end = input.parse::&lt;LitInt&gt;()?.base10_parse()?;// 解析结束数字
        input.parse::&lt;Comma&gt;()?;// 解析逗号
        let ident =input.parse::&lt;Ident&gt;()?; // 解析使用什么去定义泛型参数

        Ok(AllTuples {
            macro_ident,
            start,
            end,
            ident,
        })
    }
}

#[proc_macro]
pub fn all_tuples(input: TokenStream) -&gt; TokenStream {
    let input = parse_macro_input!(input as AllTuples);
    let len = input.end - input.start;
    let mut ident_tuples = Vec::with_capacity(len);
    for i in input.start..=input.end {
        let ident = format_ident!(&quot;{}{}&quot;, input.ident, i);
        ident_tuples.push(quote! {
<span class="boring">            ident
</span>        });
    }

    let macro_ident = &amp;input.macro_ident;
    let invocations = (input.start..=input.end).map(|i| {
        let ident_tuples = &amp;ident_tuples[..i];
        quote! {
<span class="boring">            macro_ident!(#(#ident_tuples),*);
</span>        }
    });
    TokenStream::from(quote! {
<span class="boring">        (
</span><span class="boring">            invocations
</span>        )*
    })
}
<span class="boring">}
</span></code></pre></pre>
<p>使用此过程宏，替换之前的写法，支持最多16个参数，现在代码简洁了很多，代码如下：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>all_tuples!(impl_system_param_functions, 0, 15, P);
<span class="boring">}
</span></code></pre></pre>
<p><code>all_tuples</code>是一个嵌套宏，宏展开后，生成了宏,此宏进行一次展开后变成了如下代码：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl_system_param_functions!();
impl_system_param_functions!(P0 );
impl_system_param_functions!(P0 , P1 );
impl_system_param_functions!(P0 , P1 , P2 );
impl_system_param_functions!(P0 , P1 , P2 , P3 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 , P7 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 , P7 , P8 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 , P10 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 , P10 , P11 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 , P10 , P11 , P12 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 , P10 , P11 , P12 , P13 );
impl_system_param_functions!(P0 , P1 , P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 , P10 , P11 , P12 , P13 , P14 );
<span class="boring">}
</span></code></pre></pre>
<p><code>AllTuples</code>将会是如下数据</p>
<pre><code class="language-text">{
    macro_ident: impl_system_param_functions,
    start: 0,
    end: 15,
    ident: P,
}
</code></pre>
<p>再为<code>(SystemParam,...)</code>这种内部成员全部实现了<code>SystemParam</code>的元组实现<code>SystemParam</code>，实现代码如下：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>macro_rules! impl_tuple_system_param {
    ($($param: ident),*) =&gt; {
        impl&lt;$($param: SystemParam,)*&gt; SystemParam
            for ($($param,)*)
        {
        }
    };
}

my_all_tuples!(impl_tuple_system_param, 0, 15, P);
<span class="boring">}
</span></code></pre></pre>
<h3 id="为systemparamfunction实现system"><a class="header" href="#为systemparamfunction实现system">为<code>SystemParamFunction</code>实现<code>System</code></a></h3>
<p>现在问题转到了为<code>SystemParamFunction</code>实现<code>System</code>，尝试去实现它</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;F, Param&gt; System for F
where
    F: SystemParamFunction&lt;Param&gt;,
{
    fn run(&amp;mut self) {
        self.run(todo!()) // 暂时使用 todo!() 做占位
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>但是出现了错误，&quot;Param unconstrained type parameter&quot;，<code>Param</code>未受到限制， 即没有出现在 <code>System</code> 中，也没有作为<code>SystemParamFunction</code>的关联类型，这只是作为<code>SystemParamFunction</code>的泛型参数，并没有被限制</p>
<p>为<code>System</code>添加泛型参数是不行的，因为它已经在<code>App</code>被作为了<code>dyn trait</code> <code>Box&lt;dyn System&gt;</code>，它需要动态派发</p>
<p>此时陷入了困境</p>
<p>想了想，<code>System</code>确实和<code>SystemParam</code>有关联，但是又不能直接关联，因为它被<code>App</code>作为了<code>dyn trait</code>，而<code>App</code>其实也不关注<code>System</code>的<code>SystemParam</code>是什么，不需要给<code>System</code>喂<code>SystemParam</code>，只要能调用<code>System</code>就行</p>
<p>引入中间层或者说拆分接口是一种常用的解决编程问题的方法，使用此方法就能够解决此时的问题，具体如下：</p>
<p>对<code>SystemParamFunction</code>进行包裹，定义一个新的<code>FunctionSystem</code>结构体，<code>SystemParamFunction</code>作为它的字段</p>
<p>从为<code>SystemParamFunction</code>实现<code>System</code>，转而 为<code>FunctionSystem</code>实现<code>System</code>，而<code>FunctionSystem</code>中有<code>SystemParamFunction</code>作为它的字段，<code>FunctionSystem</code>就类似于中间层</p>
<p>无法为<code>System</code>添加<code>SystemParam</code>泛型，但是引入了<code>FunctionSystem</code>后，可以为<code>FunctionSystem</code>添加<code>SystemParam</code>泛型！于是就解决了问题</p>
<p>代码如下：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct FunctionSystem&lt;F, Param&gt;
where
    Param: SystemParam + 'static,
    F: SystemParamFunction&lt;Param&gt;,
{
    func: F,
    _maker: PhantomData&lt;Param&gt;,
}

impl&lt;Param: SystemParam, F: SystemParamFunction&lt;Param&gt;&gt; System for FunctionSystem&lt;F, Param&gt; {
    fn run(&amp;mut self) {
        (self.func)(todo()!);
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>修改<code>App</code>相关代码，代码如下</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl App {
   // ...

    pub fn add_system&lt;P: SystemParam + 'static&gt;(
        &amp;mut self,
        func: impl SystemParamFunction&lt;P&gt;,
    ) -&gt; &amp;mut Self {
        self.systems.push(Box::new(FunctionSystem {
            func,
            _maker: PhantomData,
        }));
        self
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>现在代码编译成功！但是现在还无法运行，因为具体参数值还没有给，只用了<code>todo!()</code>做了占位</p>
<h3 id="参数的获取"><a class="header" href="#参数的获取">参数的获取</a></h3>
<p>定义一个新的 trait <code>SystemParamState</code>，并用<code>SystemParam</code>关联它，<code>SystemParamState</code>用于去获取<code>SystemParam</code>。</p>
<p>添加一个<code>World</code>结构体，这里我们只简单的从<code>World</code>中获取数据，为<code>System</code>的<code>run</code>方法参数添加<code>World</code>引用。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait System {
    fn run(&amp;mut self, world: &amp;World);
}

pub trait SystemParam {
    type State: SystemParamState&lt;Item = Self&gt;;
}

pub trait SystemParamState {
    type Item: SystemParam&lt;State = Self&gt;;

    fn init() -&gt; Self;

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item;
}

#[derive(Debug,Clone)]
pub struct TestSystemParam {
    test: String,
}

pub struct World {
    test_string: String,
    test_param: TestSystemParam,
}


pub struct TestStringState;

impl SystemParam for String {
    type State = TestStringState;
}

impl SystemParamState for TestStringState {
    type Item = String;

    fn init() -&gt; Self {
        TestStringState
    }

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item {
        world.test_string.clone()
    }
}

pub struct TestSystemParamState;

impl SystemParam for TestSystemParam {
    type State = TestSystemParamState;
}

impl SystemParamState for TestSystemParamState {
    type Item = TestSystemParam;

    fn init() -&gt; Self { TestSystemParamState }

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item {
        world.test_param.clone()
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>还需要为<code>(SystemParamState,...)</code>实现<code>SystemParamState</code>，与之前一样，使用宏去生成它</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>macro_rules! impl_tuple_state {
    ($($param: ident),*) =&gt; {
        #[allow(non_snake_case)]
        #[allow(clippy::unused_unit)]
        impl&lt;$($param),*&gt; SystemParamState for ($($param,)*)
        where
            $($param: SystemParamState,)*
        {
            type Item = ($($param::Item,)*);

            fn init() -&gt; Self{
                ($($param::init(),)*)
            }

            fn get_param(
                state: &amp;mut Self,
                world: &amp;World
            ) -&gt; Self::Item{
                let ($($param,)*) = state;
                ($($param::get_param($param,world),)*)
            }
        }
    };
}

all_tuples!(impl_tuple_state, 0, 15, F);
<span class="boring">}
</span></code></pre></pre>
<p>代码编译并成功运行，汇总代码如下：</p>
<pre><pre class="playground"><code class="language-rust">use std::marker::PhantomData;
use macros::all_tuples;

fn main() {
    App::new()
        .add_system(test_system)
        .add_system(test_system2)
        .add_system(test_system3)
        .run();
}

fn test_system() {
    println!(&quot;test_system&quot;);
}

fn test_system2(str: String) {
    println!(&quot;test_system2 params:{}&quot;, str);
}

fn test_system3(s: String, test: TestSystemParam, nest: (String, (String, TestSystemParam))) {
    println!(&quot;test_system3 params:{},{:?},{:?}&quot;, s, test, nest);
}

pub trait System {
    fn run(&amp;mut self, world: &amp;World);
}

#[derive(Debug,Clone)]
pub struct TestSystemParam {
    test: String,
}

pub struct World {
    test_string: String,
    test_param: TestSystemParam,
}

pub struct App {
    systems: Vec&lt;Box&lt;dyn System&gt;&gt;,
    world: World,
}

impl App {
    pub fn new() -&gt; Self {
        Self {
            systems: vec![],
            world: World {
                test_string: String::from(&quot;test String&quot;),
                test_param: TestSystemParam {
                    test: String::from(&quot;TestSystemParam&quot;),
                },
            },
        }
    }

    pub fn add_system&lt;P: SystemParam + 'static&gt;(
        &amp;mut self,
        func: impl SystemParamFunction&lt;P&gt;,
    ) -&gt; &amp;mut Self {
        self.systems.push(Box::new(FunctionSystem {
            func,
            state: P::State::init(),
            _maker: PhantomData,
        }));
        self
    }

    pub fn run(&amp;mut self) {
        for item in self.systems.iter_mut() {
            item.run(&amp;self.world);
        }
    }
}

pub trait SystemParam {
    type State: SystemParamState&lt;Item = Self&gt;;
}

pub trait SystemParamState {
    type Item: SystemParam&lt;State = Self&gt;;

    fn init() -&gt; Self;

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item;
}

pub struct TestStringState;

impl SystemParam for String {
    type State = TestStringState;
}

impl SystemParamState for TestStringState {
    type Item = String;

    fn init() -&gt; Self {
        TestStringState
    }

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item {
        world.test_string.clone()
    }
}

pub struct TestSystemParamState;

impl SystemParam for TestSystemParam {
    type State = TestSystemParamState;
}

impl SystemParamState for TestSystemParamState {
    type Item = TestSystemParam;

    fn init() -&gt; Self { TestSystemParamState }

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item {
        world.test_param.clone()
    }
}

pub struct FunctionSystem&lt;F, Param&gt;
where
    Param: SystemParam + 'static,
    F: SystemParamFunction&lt;Param&gt;,
{
    func: F,
    state: Param::State,
    _maker: PhantomData&lt;Param&gt;,
}

impl&lt;Param: SystemParam, F: SystemParamFunction&lt;Param&gt;&gt; System for FunctionSystem&lt;F, Param&gt; {
    fn run(&amp;mut self, world: &amp;World) {
        let param = Param::State::get_param(&amp;mut self.state, world);
        self.func.run(param)
    }
}

pub trait SystemParamFunction&lt;Param&gt;: 'static {
    fn run(&amp;mut self, params: Param);
}

macro_rules! impl_system_param_functions {
    ($($param: ident),*) =&gt; {
        impl&lt;F,$($param),*&gt; SystemParamFunction&lt;($($param,)*)&gt; for F
        where
            F: FnMut($($param),*) + 'static,
        {
            fn run(&amp;mut self, ($($param,)*): ($($param,)*)) {
                (self)($($param),*);
            }
        }
    };
}

all_tuples!(impl_system_param_functions, 0, 15, P);

macro_rules! impl_tuple_system_param {
    ($($param: ident),*) =&gt; {
        impl&lt;$($param: SystemParam,)*&gt; SystemParam
            for ($($param,)*)
        {
            type State = ($($param::State,)*);
        }
    };
}

all_tuples!(impl_tuple_system_param, 0, 15, P);

macro_rules! impl_tuple_state {
    ($($param: ident),*) =&gt; {
        #[allow(non_snake_case)]
        #[allow(clippy::unused_unit)]
        impl&lt;$($param),*&gt; SystemParamState for ($($param,)*)
        where
            $($param: SystemParamState,)*
        {
            type Item = ($($param::Item,)*);

            fn init() -&gt; Self{
                ($($param::init(),)*)
            }

            fn get_param(
                state: &amp;mut Self,
                world: &amp;World
            ) -&gt; Self::Item{
                let ($($param,)*) = state;
                ($($param::get_param($param,world),)*)
            }
        }
    };
}

all_tuples!(impl_tuple_state, 0, 15, F);
</code></pre></pre>
<h3 id="intosystem"><a class="header" href="#intosystem">IntoSystem</a></h3>
<p><code>App</code>的<code>add_system</code>方法现在只接受实现了<code>SystemParamFunction</code>的对象，对于实现了<code>System</code>的对象，无法进行添加，也就无法添加自定义的<code>System</code>，虽然可以为<code>App</code>添加一个新的方法去专门添加实现了<code>System</code>的对象，但是这里有一个更好的方法。</p>
<p>定义一个新的<code>IntoSystem</code> trait，他表示了能够转换<code>System</code>的能力。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait IntoSystem&lt;Param&gt;: Sized {
    type System: System;
    fn to_system(self) -&gt; Self::System;
}
<span class="boring">}
</span></code></pre></pre>
<p>修改<code>App</code></p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl App {
    // ...

    pub fn add_system&lt;Param&gt;(&amp;mut self, system: impl IntoSystem&lt;Param&gt;) -&gt; &amp;mut Self {
        self.systems.push(Box::new(system.to_system()));
        self
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>这样所有能够转换到<code>System</code>的对象都可以进行添加，</p>
<p>再为<code>SystemParamFunction</code>与<code>System</code>实现<code>IntoSystem</code></p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;Param: SystemParam + 'static, F: SystemParamFunction&lt;Param&gt;&gt; IntoSystem&lt;Param&gt; for F {
    type System = FunctionSystem&lt;F, Param&gt;;

    fn to_system(self) -&gt; Self::System {
        FunctionSystem {
            func: self,
            state: Param::State::init(),
            _maker: PhantomData,
        }
    }
}

pub struct AlreadyWasSystem;

impl&lt;S: System&gt; IntoSystem&lt;AlreadyWasSystem&gt; for S {
    type System = Self;

    fn to_system(self) -&gt; Self::System {
        self
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>你可能注意到了<code>AlreadyWasSystem</code>，因为自定义<code>System</code>是没有<code>Param</code>的，所以实现<code>System</code>时<code>Param</code>泛型参数使用<code>AlreadyWasSystem</code>结构体作为标记，也规避了重复实现的错误，为什么会重复实现<code>IntoSystem&lt;Param&gt;</code>？假如这里没有做区分，一个结构体同时实现了<code>System</code>与<code>SystemParamFunction</code>，此结构体就会实现两次<code>IntoSystem</code>，rust 不允许这种出现重复实现的可能性!对<code>IntoSystem</code>的<code>Param</code>泛型参数做区分，同时实现了<code>System</code>与<code>SystemParamFunction</code>的结构体将实现不同的<code>IntoSystem</code></p>
<blockquote>
<p>提示：注意为<code>System</code>与<code>SystemParam</code>添加<code>'static</code>约束，否则会有生命周期问题，<code>'static</code>约束表示对应结构没有<code>非'static</code>借用（或者说没有生命周期标记泛型），生命周期也将完全由自己掌控</p>
</blockquote>
<p>代码完成，添加<code>CustomSystem</code>、匿名函数、闭包、普通函数和嵌套参数函数的运行测试</p>
<p>汇总代码如下：</p>
<pre><pre class="playground"><code class="language-rust">use std::marker::PhantomData;

use macros::all_tuples;

pub struct CustomSystem;

impl System for CustomSystem {
    fn run(&amp;mut self, world: &amp;World) {
        println!(&quot;CustomSystem: Hello!&quot;)
    }
}

fn main() {
    let str = &quot;Closure: Hello&quot;;

    let fun: fn() = || println!(&quot;Anonymous Fun: Hello&quot;);

    App::new()
        .add_system(test_system)
        .add_system(test_system2)
        .add_system(test_system3)
        .add_system(CustomSystem)
        .add_system(fun)
        .add_system(move || {
            println!(&quot;{}&quot;, str);
        })
        .run();
}

fn test_system() {
    println!(&quot;test_system&quot;);
}

fn test_system2(str: String) {
    println!(&quot;test_system2 params:{}&quot;, str);
}

fn test_system3(s: String, test: TestSystemParam, nest: (String, (String, TestSystemParam))) {
    println!(&quot;test_system3 params:{},{:?},{:?}&quot;, s, test, nest);
}

pub trait System: 'static {
    fn run(&amp;mut self, world: &amp;World);
}

#[derive(Debug, Clone)]
pub struct TestSystemParam {
    test: String,
}

pub struct World {
    test_string: String,
    test_param: TestSystemParam,
}

pub struct App {
    systems: Vec&lt;Box&lt;dyn System&gt;&gt;,
    world: World,
}

impl App {
    pub fn new() -&gt; Self {
        Self {
            systems: vec![],
            world: World {
                test_string: String::from(&quot;test String&quot;),
                test_param: TestSystemParam {
                    test: String::from(&quot;TestSystemParam&quot;),
                },
            },
        }
    }

    pub fn add_system&lt;Param&gt;(&amp;mut self, system: impl IntoSystem&lt;Param&gt;) -&gt; &amp;mut Self {
        self.systems.push(Box::new(system.to_system()));
        self
    }

    pub fn run(&amp;mut self) {
        for item in self.systems.iter_mut() {
            item.run(&amp;self.world);
        }
    }
}

pub trait SystemParam {
    type State: SystemParamState&lt;Item = Self&gt;;
}

pub trait SystemParamState {
    type Item: SystemParam&lt;State = Self&gt;;

    fn init() -&gt; Self;

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item;
}
pub struct TestStringState;

impl SystemParam for String {
    type State = TestStringState;
}

impl SystemParamState for TestStringState {
    type Item = String;

    fn init() -&gt; Self {
        TestStringState
    }

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item {
        world.test_string.clone()
    }
}

pub struct TestSystemParamState;

impl SystemParam for TestSystemParam {
    type State = TestSystemParamState;
}

impl SystemParamState for TestSystemParamState {
    type Item = TestSystemParam;

    fn init() -&gt; Self { TestSystemParamState }

    fn get_param(state: &amp;mut Self, world: &amp;World) -&gt; Self::Item {
        world.test_param.clone()
    }
}

pub struct FunctionSystem&lt;F, Param&gt;
where
    Param: SystemParam + 'static,
    F: SystemParamFunction&lt;Param&gt;,
{
    func: F,
    state: Param::State,
    _maker: PhantomData&lt;Param&gt;,
}

impl&lt;Param: SystemParam, F: SystemParamFunction&lt;Param&gt;&gt; System for FunctionSystem&lt;F, Param&gt; {
    fn run(&amp;mut self, world: &amp;World) {
        let param = Param::State::get_param(&amp;mut self.state, world);
        self.func.run(param)
    }
}

pub trait IntoSystem&lt;Param&gt;: Sized {
    type System: System;
    fn to_system(self) -&gt; Self::System;
}

impl&lt;Param: SystemParam + 'static, F: SystemParamFunction&lt;Param&gt;&gt; IntoSystem&lt;Param&gt; for F {
    type System = FunctionSystem&lt;F, Param&gt;;

    fn to_system(self) -&gt; Self::System {
        FunctionSystem {
            func: self,
            state: Param::State::init(),
            _maker: PhantomData,
        }
    }
}

pub struct AlreadyWasSystem;

impl&lt;S: System&gt; IntoSystem&lt;AlreadyWasSystem&gt; for S {
    type System = Self;

    fn to_system(self) -&gt; Self::System {
        self
    }
}

pub trait SystemParamFunction&lt;Param&gt;: 'static {
    fn run(&amp;mut self, params: Param);
}

macro_rules! impl_system_param_functions {
    ($($param: ident),*) =&gt; {
        impl&lt;F,$($param),*&gt; SystemParamFunction&lt;($($param,)*)&gt; for F
        where
            F: FnMut($($param),*) + 'static,
        {
            fn run(&amp;mut self, ($($param,)*): ($($param,)*)) {
                (self)($($param),*);
            }
        }
    };
}

all_tuples!(impl_system_param_functions, 0, 15, P);

macro_rules! impl_tuple_system_param {
    ($($param: ident),*) =&gt; {
        impl&lt;$($param: SystemParam,)*&gt; SystemParam
            for ($($param,)*)
        {
            type State = ($($param::State,)*);
        }
    };
}

all_tuples!(impl_tuple_system_param, 0, 15, P);

macro_rules! impl_tuple_state {
    ($($param: ident),*) =&gt; {
        #[allow(non_snake_case)]
        #[allow(clippy::unused_unit)]
        impl&lt;$($param),*&gt; SystemParamState for ($($param,)*)
        where
            $($param: SystemParamState,)*
        {
            type Item = ($($param::Item,)*);

            fn init() -&gt; Self{
                ($($param::init(),)*)
            }

            fn get_param(
                state: &amp;mut Self,
                world: &amp;World
            ) -&gt; Self::Item{
                let ($($param,)*) = state;
                ($($param::get_param($param,world),)*)
            }
        }
    };
}

all_tuples!(impl_tuple_state, 0, 15, F);
</code></pre></pre>
<p>宏代码</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// 描述宏需要解析到的数据
struct AllTuples {
    macro_ident: Ident,
    start: usize,
    end: usize,
    ident: Ident,
}

impl Parse for AllTuples {
    fn parse(input: ParseStream) -&gt; Result&lt;Self&gt; {
        let macro_ident = input.parse::&lt;Ident&gt;()?; // 解析使用哪个宏定义
        input.parse::&lt;Comma&gt;()?;// 解析逗号
        let start = input.parse::&lt;LitInt&gt;()?.base10_parse()?; // 解析开始数字
        input.parse::&lt;Comma&gt;()?;// 解析逗号
        let end = input.parse::&lt;LitInt&gt;()?.base10_parse()?;// 解析结束数字
        input.parse::&lt;Comma&gt;()?;// 解析逗号
        let ident =input.parse::&lt;Ident&gt;()?; // 解析使用什么去定义泛型参数

        Ok(AllTuples {
            macro_ident,
            start,
            end,
            ident,
        })
    }
}

#[proc_macro]
pub fn all_tuples(input: TokenStream) -&gt; TokenStream {
    let input = parse_macro_input!(input as AllTuples);
    let len = input.end - input.start;
    let mut ident_tuples = Vec::with_capacity(len);
    for i in input.start..=input.end {
        let ident = format_ident!(&quot;{}{}&quot;, input.ident, i);
        ident_tuples.push(quote! {
<span class="boring">            ident
</span>        });
    }

    let macro_ident = &amp;input.macro_ident;
    let invocations = (input.start..=input.end).map(|i| {
        let ident_tuples = &amp;ident_tuples[..i];
        quote! {
<span class="boring">            macro_ident!(#(#ident_tuples),*);
</span>        }
    });
    TokenStream::from(quote! {
<span class="boring">        (
</span><span class="boring">            invocations
</span>        )*
    })
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="总结"><a class="header" href="#总结">总结</a></h3>
<ul>
<li><code>SystemParam</code>表示了可以作为<code>System</code>参数的能力，同时为成员都是<code>SystemParam</code>的元组实现<code>SystemParam</code></li>
<li><code>SystemParamFunction</code>对<code>FuMut</code>进行了包裹，<code>SystemParamFunction</code>的<code>Param</code>泛型只接受元组<code>SystemParam</code>，将元组成员作为参数调用<code>FuMut</code></li>
<li><code>FunctionSystem</code>作为<code>System</code>与<code>SystemParamFunction</code>的&quot;中间层&quot;，解决<code>System</code>无法关联<code>SystemParam</code>的问题</li>
<li>通过宏生成与<code>SystemParam</code>元组相关的实现</li>
<li><code>SystemParam</code>关联了<code>SystemParamState</code>，<code>SystemParamState</code>实现了如何去获取对于的<code>SystemParam</code>值</li>
<li><code>IntoSystem</code> trait，他表示了能够转换到<code>System</code>的能力，所有<code>IntoSystem</code>的实现都可以添加到<code>App</code>中，优雅的提升了扩展性，灵活性</li>
</ul>
<h3 id="文章更新记录"><a class="header" href="#文章更新记录">文章更新记录</a></h3>
<ul>
<li>2022-12-29: 添加了一些关于<code>all_tuples</code>宏的注释，删除一些无用的代码，修复一些用法错误</li>
<li>2022-12-30：添加总结，补充宏代码，添加匿名函数与闭包的打印测试，补充一些说明，修复错别字</li>
<li>2023-01-19：调整代码顺序</li>
<li>2023-03-29：纠正错误</li>
</ul>
<h3 id="end"><a class="header" href="#end">End</a></h3>
<p>如果文章内容有任何问题，你可以评论区告诉我</p>
<blockquote>
<p>欢迎喜爱 rust 的 rustacean 加入QQ频道一起学习交流：<a href="https://link.zhihu.com/?target=https%3A//qun.qq.com/qqweb/qunpro/share%3F_wv%3D3%26_wwv%3D128%26appChannel%3Dshare%26inviteCode%3D1XRJqIu2xQD%26businessType%3D9%26jumpInfo%3DChCRorhoHUBLezzxc51XLGeBEgN2cDE%3D%26from%3D246610%26biz%3Dka%23/pc">Rust 编程语言同好，频道号：wz3qv8dszc</a></p>
</blockquote>
<p>编辑于 2023-03-29 13:37・IP 属地江西</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
